<?php

namespace App\Exceptions;

use App\Exceptions\HttpErrorHandler;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Exception\HttpInternalServerErrorException;
use Slim\ResponseEmitter;

class ShutdownHandler
{
    private $request;

    private $errorHandler;

    private $displayErrorDetails;

    public function __construct(
        ServerRequestInterface $request,
        HttpErrorHandler $errorHandler,
        bool $displayErrorDetails
    ) {
        $this->request = $request;
        $this->errorHandler = $errorHandler;
        $this->displayErrorDetails = $displayErrorDetails;
    }

    public function __invoke()
    {
        $error = error_get_last();
        if (is_null($error)) {
            return true;
        }

        if (!isset($error['type']) || !isset($error['message']) ||
            !isset($error['file']) || !isset($error['line'])
        ) {
            $message = 'An error while processing your request. Please try again later.';
        } else {
            $message = '';
            switch ($error['type']) {
                case E_USER_ERROR:
                    $message = 'FATAL ERROR: ' . $error['message'] . '. ';
                    $message .= 'on line ' . $error['line'] . ' in file ' . $error['file'];
                    break;
                case E_USER_WARNING:
                    $message = 'WARNING: ' . $error['message'];
                    break;
                case E_USER_NOTICE:
                    $message = 'NOTICE: ' . $error['message'];
                    break;
                default:
                    $message = 'ERROR: ' . $error['message'] . '. ';
                    $message .= 'on line ' . $error['line'] . ' in file ' . $error['file'];
                    break;
            }
        }

        $exception = new HttpInternalServerErrorException($this->request, $message);
        $response = $this->errorHandler->__invoke(
            $this->request,
            $exception,
            $this->displayErrorDetails,
            false,
            false
        );

        if (ob_get_length()) {
            ob_clean();
        }

        $responseEmitter = new ResponseEmitter;
        $responseEmitter->emit($response);
    }
}
